// app.js
import Api from "./utils/http/api";
import config from "./utils/http/config";

const common_utils = require('./utils/common_utils.js')
App({
  onLaunch(options) {
    let user_id = common_utils.getLocalStorageData('user_id');
    if (user_id) {
      this.globalData.loginFlag = true
    }
    // 获取其他小程序传递过来的参数
    if (options.referrerInfo.extraData) {
      this.globalData.extraData = options.referrerInfo.extraData

    }
    // this.getUpdateAppInfo();
    this.getNavBarInfo();
    this.getOpenId()

  },
  /**
   * @desc 检查更新小程序
   */
  getUpdateAppInfo() {
    const updateManager = wx.getUpdateManager();
    if (updateManager) {
      updateManager.onCheckForUpdate((res) => {
        // 请求完新版本信息的回调
        console.log(res.hasUpdate)
      })

      updateManager.onUpdateReady(() => {
        wx.showModal({
          title: '更新提示',
          content: '新版本已经准备好，是否重启应用？',
          success: (res) => {
            if (res.confirm) {
              // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
              updateManager.applyUpdate()
            }
          }
        })
      })
    }
  },



  /**
   * @desc 获取状态栏的相关信息
   */
  getNavBarInfo() {
    let menuButtonObject = wx.getMenuButtonBoundingClientRect();
    wx.getSystemInfo({
      success: res => {
        let statusBarHeight = res.statusBarHeight,
          navTop = menuButtonObject.top, //胶囊按钮与顶部的距离
          navHeight = statusBarHeight + menuButtonObject.height + (menuButtonObject.top - statusBarHeight) * 2; //导航高度
        this.globalData.navHeight = navHeight; //导航栏总高度
        this.globalData.titleHeight = navHeight - statusBarHeight; //胶囊栏高度
        //自适应rpx为单位
        let safeAreaObject = res.safeArea; // 在竖屏正方向下的安全区域
        let pixelRatio = 750 / wx.getSystemInfoSync().windowWidth; // 适配
        let spacingHeight = (menuButtonObject.top - safeAreaObject.top) * pixelRatio //  胶囊顶部到状态栏的剩余间距 = 胶囊顶部-电量状态栏高度
        let navBottom = menuButtonObject.bottom * pixelRatio //胶囊按钮底部与顶部的距离
        let statusBarHeightRpx = safeAreaObject.top * pixelRatio;
        let navigationBarHeightRpx = navBottom + spacingHeight;
        this.globalData.windowHeight = res.windowHeight;
        this.globalData.pixelRatio = pixelRatio // 1像素比，单位是：rpx
        this.globalData.statusBarHeightRpx = statusBarHeightRpx // 信号电池等状态栏高度，单位是：rpx
        this.globalData.navigationBarHeightRpx = navigationBarHeightRpx // ->(整个状态栏的高度：状态栏+标题栏，单位是：rpx)
      },
      fail(err) {
        console.log(err);
      }
    })
  },

  // 获取用户唯一表示
  getOpenId() {
    wx.login({
      success: res => {
        Api.getOpenId({
          jscode: res.code
        }).then(res => {
          wx.setStorageSync('open_id', res.data.openid)
          wx.setStorageSync('session_key', res.data.session_key)

        })
      },
      fail: res => {}
    })
  },
  // 全局变量
  globalData: {
    loginFlag: false,
    pixelRatio: 2,
    navigationBarHeightRpx: '',
  },
})